<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        @submit.native.prevent
        label-width="90px"
      >
        <el-form-item label="路由名称" prop="routeName">
          <common-input
            :verify="false"
            @enter="handleQuery"
            v-model="queryParams.routeName"
            clearable
          />
        </el-form-item>
        <el-form-item label="路由标识ID" prop="routeId">
          <common-input
            :verify="false"
            v-model="queryParams.routeId"
            @enter="handleQuery"
            clearable
          />
        </el-form-item>
        <el-form-item label="资源标识URL" prop="uri">
          <common-input
            :verify="false"
            @enter="handleQuery"
            v-model="queryParams.uri"
            :maxlength="256"
            clearable
          />
        </el-form-item>
        <el-form-item label="认证方式" prop="controlType">
          <el-select
            v-model="queryParams.controlType"
            placeholder="请选择"
            clearable
          >
            <el-option label="全部" :value="null" />
            <el-option label="不认证" value="0" />
            <el-option label="基础认证" value="1" />
            <el-option label="OAuth2" value="2" />
            <el-option label="JWT认证" value="3" />
            <el-option label="LDAP认证" value="4" />
            <el-option label="Key Authentication 密钥" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属网关" prop="dataId">
          <el-select
            v-model="queryParams.dataId"
            placeholder="请选择"
            clearable
          >
            <el-option label="全部" :value="null" />
            <el-option
              v-for="(item, index) in dictData"
              :label="item.dictLabel"
              :value="item.dictLabel"
              :key="index"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row :gutter="10" class="mb8" slot="tools">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['system:routing:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:routing:remove']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>

    <common-table
      slot="content"
      v-loading="loading"
      :data="routesConfigList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="路由名称"
        align="left"
        prop="routeName"
        show-overflow-tooltip
      />
      <el-table-column
        label="路由标识ID"
        align="left"
        prop="routeId"
        show-overflow-tooltip
      />
      <el-table-column
        label="资源标识URL"
        align="left"
        prop="uri"
        show-overflow-tooltip
      />
      <el-table-column
        label="服务前缀"
        align="left"
        prop="predicates"
        show-overflow-tooltip
      />
      <el-table-column
        label="认证方式"
        align="left"
        prop="controlType"
        show-overflow-tooltip
        ><template slot-scope="{ row }">
          {{
            row.controlType === "0"
              ? "不认证"
              : row.controlType === "1"
              ? "基础认证"
              : row.controlType === "2"
              ? "OAuth2"
              : row.controlType === "3"
              ? "JWT认证"
              : row.controlType === "4"
              ? "LDAP认证"
              : row.controlType === "5"
              ? "Key Authentication 密钥"
              : ""
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="所属网关"
        align="left"
        prop="dataId"
        show-overflow-tooltip
      />

      <el-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="190"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="getPassUrl(scope.row)"
            v-hasPermi="['system:passurl:list']"
            >应用白名单
          </el-button>
          <el-button
            type="text"
            @click="getInfo(scope.row, 2)"
            v-hasPermi="['system:routing:detail']"
            >详情
          </el-button>
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:routing:update']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:routing:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getRoutesConfig"
    />

    <!-- 添加或编辑服务路由管理对话框 -->
    <common-edit-dialog
      :title="title"
      :visible.sync="open"
      @cancel="cancel"
      @submit="submitForm"
      :buttonLoading="buttonLoading"
      :info-loading="infoUpdateLoading"
    >
      <CommonGroupTitle title="基本信息"></CommonGroupTitle>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.native.prevent
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="路由名称" prop="routeName">
              <common-input
                v-model="form.routeName"
                placeholder="请输入"
                :maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="路由标识ID" prop="routeId">
              <common-input
                :disabled="title === '编辑路由管理' ? true : false"
                :verify="false"
                v-model="form.routeId"
                placeholder="ark-system"
                :maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="资源标识URL" prop="uri">
              <common-input
                :verify="false"
                v-model="form.uri"
                placeholder="lb://ark-system"
                :maxlength="128"
              >
              </common-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务前缀" prop="predicates">
              <common-input
                :verify="false"
                v-model="predicates"
                :placeholder="placeholders"
              >
                <el-select
                  v-model="predicatesHead"
                  style="width: 100px"
                  placeholder="请选择"
                  @change="predicatesHeadChange(predicatesHead)"
                  slot="prepend"
                >
                  <el-option label="Path=" value="Path=" />
                  <el-option label="Host=" value="Host=" />
                </el-select>
              </common-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="过滤器规则" prop="filters">
              <el-select
                v-model="filters"
                placeholder="请选择"
                clearable
                style="width: 49%"
                @change="filtersChange(filters)"
              >
                <el-option label="StripPrefix" value="StripPrefix=" />
              </el-select>
              <el-select
                v-model="filtersValue"
                placeholder="请选择"
                clearable
                :disabled="filtersValueDisabled"
                style="width: 49%; margin-left: 2%"
              >
                <el-option label="1" value="1" />
                <el-option label="2" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属网关" prop="dataId">
              <el-select
                v-model="form.dataId"
                placeholder="请选择"
                clearable
                :disabled="isDataId"
              >
                <el-option
                  v-for="(item, index) in dictData"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  :key="index"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24" v-if="strategyDisplay">
          <!--   <el-col :span="12" v-if="strategyDisplay">
            <el-form-item label="策略类型" prop="controlType">
              <el-select
                v-model="form.controlType"
                placeholder="请选择"
                clearable
                @change="controlTypeChange(form.controlType)"
              >
                <el-option label="放行" value="ALLOW" />
                <el-option label="拦截" value="REFUSE" />
              <el-option label="限流" value="LIMIT" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24" v-if="controlTypeDisplay">
            <el-form-item label="管控策略" prop="controlPolicy">
              <div
                v-for="(item, i) in controlPolicy"
                :key="i"
                class="displayFlex"
              >
                <common-input
                  :verify="false"
                  v-model="controlPolicyArr[i]"
                  placeholder="请输入格式如：ip:192.168.2.239 或 ip段:192.168.2.45/239"
                >
                </common-input>
                <el-button
                  v-if="controlPolicy.length > 1"
                  class="delectCurrentParam"
                  @click="delcontrolPolicyFn(i)"
                  style="margin-left: 10px; font-size: 12px"
                  type="danger"
                  plain
                  >删除
                </el-button>
                <el-button
                  v-if="i === 0"
                  type="primary"
                  @click="controlPolicyFn"
                  style="margin-left: 10px"
                  plain
                  >新增
                </el-button>
              </div>
            </el-form-item>
          </el-col> -->
        </el-row>
        <CommonGroupTitle title="认证方式"></CommonGroupTitle>
        <el-row>
          <el-col :span="24">
            <el-form-item label="认证方式" prop="controlType">
              <el-select
                v-model="form.controlType"
                placeholder="请选择"
                clearable
                @change="oauthTypeChange(form.controlType)"
              >
                <el-option label="不认证" value="0" />
                <el-option label="基础认证" value="1" />
                <el-option label="OAuth2" value="2" />
                <el-option label="JWT认证" value="3" />
                <el-option label="LDAP认证" value="4" />
                <el-option label="Key Authentication 密钥" value="5" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="form.controlType === '3'">
            <el-form-item label="秘钥" prop="secretKey">
              <common-input
                :verify="false"
                type="password"
                v-model="form.secretKey"
                placeholder="请输入"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>

          <el-col
            :span="12"
            v-if="
              form.controlType === '2' ||
              form.controlType === '3' ||
              form.controlType === '4' ||
              form.controlType === '5'
            "
          >
            <el-form-item label="TOKEN位置" prop="tokenPosition">
              <el-select
                v-model="form.tokenPosition"
                placeholder="请选择"
                clearable
              >
                <el-option label="header" value="header" />
                <el-option label="param" value="param" />
                <el-option label="cookie" value="cookie" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="
              form.controlType === '2' ||
              form.controlType === '3' ||
              form.controlType === '4' ||
              form.controlType === '5'
            "
          >
            <el-form-item label="TOKEN参数名称" prop="tokenName">
              <common-input
                :verify="false"
                v-model="form.tokenName"
                placeholder="请输入"
                :maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.controlType !== '0'">
            <el-form-item label="授权接口" prop="authServer">
              <common-input
                :verify="false"
                v-model="form.authServer"
                placeholder="示例：http://localhost:8080/auth/getToken"
              />
            </el-form-item>
          </el-col>

          <el-col
            :span="24"
            v-if="form.controlType === '2' || form.controlType === '4'"
          >
            <el-form-item label="鉴权接口" prop="checkAuthServer">
              <common-input
                :verify="false"
                v-model="form.checkAuthServer"
                placeholder="示例：http://localhost:8080/auth/check"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="form.controlType === '1'">
            <el-form-item
              label="鉴权接口"
              prop="checkAuthServer"
              class="check-auth-server"
            >
              <common-input
                :verify="false"
                v-model="form.checkAuthServer"
                placeholder="示例：http://localhost:8080/auth/check"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="form.controlType === '1'">
            <el-form-item label="用户名参数名称" prop="paramUser">
              <common-input
                :verify="false"
                v-model="form.paramUser"
                placeholder="请输入"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.controlType === '1'">
            <el-form-item label="密码参数名称" prop="paramPwd">
              <common-input
                :verify="false"
                v-model="form.paramPwd"
                placeholder="请输入"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.controlType === '1'">
            <el-form-item label="请求内容类型" prop="contentType">
              <el-select
                v-model="form.contentType"
                placeholder="请选择"
                clearable
              >
                <el-option label="application/json" value="application/json" />
                <el-option
                  label="application/x-www-form-urlencoded"
                  value="application/x-www-form-urlencoded"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.controlType === '1'">
            <el-form-item label="解析令牌名称" prop="paramToken">
              <common-input
                :verify="false"
                v-model="form.paramToken"
                placeholder="请输入"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="form.controlType === '2'">
            <el-form-item label="认证模式" prop="oauthType">
              <el-select
                v-model="form.oauthType"
                placeholder="请选择"
                clearable
              >
                <el-option label="授权码模式" value="code" />
                <el-option label="隐式授权模式" value="implicit" />
                <el-option label="密码模式" value="password" />
                <el-option label="客户端模式" value="client" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            v-if="form.controlType === '2' && form.oauthType === 'code'"
          >
            <el-form-item label="授权码接口" prop="callCodeUrl">
              <common-input
                :verify="false"
                v-model="form.callCodeUrl"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12" v-if="form.controlType === '2'">
            <el-form-item label="刷新token" prop="token">
              <el-radio-group v-model="form.token">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="24" v-if="form.controlType === '2'">
            <el-form-item label="回调地址" prop="Callback">
              <common-input
                :verify="false"
                v-model="form.Callback"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col> -->

          <!-- <el-col :span="24" v-if="form.controlType === '4'">
            <el-form-item label="基准域名" prop="baseAddress">
              <common-input
                :verify="false"
                v-model="form.baseAddress"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12" v-if="form.controlType === '4'">
            <el-form-item label="账号" prop="userName">
              <common-input
                :verify="false"
                v-model="form.userName"
                placeholder="请输入"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.controlType === '4'">
            <el-form-item label="密码" prop="userPwd">
              <common-input
                type="password"
                :verify="false"
                v-model="form.userPwd"
                placeholder="请输入"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.controlType === '5'">
            <el-form-item label="appKey" prop="appKey">
              <common-input
                :verify="false"
                v-model="form.appKey"
                placeholder="请输入"
                :maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.controlType === '5'">
            <el-form-item label="appSecret" prop="appSecret">
              <common-input
                :verify="false"
                v-model="form.appSecret"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.controlType !== '0'">
            <el-form-item label="描述" prop="remark">
              <common-input
                type="textarea"
                clearable
                style="width: 100%"
                v-model="form.remark"
                placeholder="请输入"
                :maxlength="256"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </common-edit-dialog>
    <common-info-dialog
      :title="detailsTitle"
      :visible.sync="detailsOpen"
      @cancel="cancel"
      :infoLoading="infoLoading"
    >
      <common-info-table>
        <common-info-table-cell label="路由名称" width="50%">
          {{ form.routeName }}
        </common-info-table-cell>
        <common-info-table-cell label="路由标识ID" width="50%">
          {{ form.routeId }}
        </common-info-table-cell>
        <common-info-table-cell label="资源标识URL" width="50%">
          {{ form.uri }}
        </common-info-table-cell>
        <common-info-table-cell label="服务前缀" width="50%">
          {{ form.predicates }}
        </common-info-table-cell>
        <common-info-table-cell label="所属网关" width="50%">
          {{ form.dataId }}
        </common-info-table-cell>
        <common-info-table-cell label="过滤器规则" width="50%">
          {{ form.filters }}
        </common-info-table-cell>
        <common-info-table-cell
          label="用户名参数名称"
          v-if="form.controlType === '1'"
        >
          {{ form.paramUser }}
        </common-info-table-cell>
        <common-info-table-cell
          label="密码参数名称"
          v-if="form.controlType === '1'"
        >
          {{ form.paramPwd }}
        </common-info-table-cell>
        <common-info-table-cell
          label="请求内容类型"
          v-if="form.controlType === '1'"
        >
          {{ form.contentType }}
        </common-info-table-cell>
        <common-info-table-cell
          label="解析令牌名称"
          v-if="form.controlType === '1'"
        >
          {{ form.paramToken }}
        </common-info-table-cell>

        <common-info-table-cell label="认证方式">
          {{
            form.controlType === "0"
              ? "不认证"
              : form.controlType === "1"
              ? "基础认证"
              : form.controlType === "2"
              ? "OAuth2"
              : form.controlType === "3"
              ? "JWT认证"
              : form.controlType === "4"
              ? "LDAP认证"
              : form.controlType === "5"
              ? "Key Authentication 密钥"
              : ""
          }}
        </common-info-table-cell>
        <common-info-table-cell
          label="TOKEN位置"
          v-if="
            form.controlType === '2' ||
            form.controlType === '3' ||
            form.controlType === '4' ||
            form.controlType === '5'
          "
        >
          {{ form.tokenPosition }}
        </common-info-table-cell>
        <common-info-table-cell
          label="TOKEN参数名称"
          v-if="
            form.controlType === '2' ||
            form.controlType === '3' ||
            form.controlType === '4' ||
            form.controlType === '5'
          "
        >
          {{ form.tokenName }}
        </common-info-table-cell>
        <common-info-table-cell
          label="鉴权接口"
          v-if="
            form.controlType === '2' ||
            form.controlType === '1' ||
            form.controlType === '4'
          "
        >
          {{ form.checkAuthServer }}
        </common-info-table-cell>
        <common-info-table-cell
          label="授权接口"
          v-if="
            form.controlType === '2' ||
            form.controlType === '4' ||
            form.controlType === '5' ||
            form.controlType === '1'
          "
        >
          {{ form.authServer }}
        </common-info-table-cell>
        <common-info-table-cell
          label="认证模式"
          v-if="form.controlType === '2'"
        >
          {{
            form.oauthType === "code"
              ? "授权码模式"
              : form.oauthType === "implicit"
              ? "隐式授权模式"
              : form.oauthType === "password"
              ? "密码模式"
              : form.oauthType === "client"
              ? "客户端模式"
              : ""
          }}
        </common-info-table-cell>
        <common-info-table-cell label="秘钥" v-if="form.controlType === '3'">
          {{ form.secretKey }}
        </common-info-table-cell>
        <!-- <common-info-table-cell
          label="基准域名"
          v-if="form.controlType === '4'"
        >
          {{ form.baseAddress }}
        </common-info-table-cell> -->
        <common-info-table-cell label="账号" v-if="form.controlType === '4'">
          {{ form.userName }}
        </common-info-table-cell>
        <common-info-table-cell label="密码" v-if="form.controlType === '4'">
          {{ form.userPwd }}
        </common-info-table-cell>
        <common-info-table-cell label="appKey" v-if="form.controlType === '5'">
          {{ form.appKey }}
        </common-info-table-cell>
        <common-info-table-cell
          label="appSecret"
          v-if="form.controlType === '5'"
        >
          {{ form.appSecret }}
        </common-info-table-cell>
        <common-info-table-cell label="描述" v-if="form.controlType !== '0'">
          {{ form.remark }}
        </common-info-table-cell>
        <!-- <common-info-table-cell label="策略类型" width="100%">
          {{
            form.controlType === "ALLOW"
              ? "放行"
              : form.controlType === "REFUSE"
              ? "拦截"
              : form.controlType === "LIMIT"
              ? "限流"
              : ""
          }}
        </common-info-table-cell> -->

        <!-- <common-info-table-cell label="管控策略" width="100%">
          {{ form.controlPolicy && form.controlPolicy.join() }}
        </common-info-table-cell> -->
        <!--        <common-info-table-cell label="路径控制">-->
        <!--          {{ form.blacklistUrl }}-->
        <!--        </common-info-table-cell>-->
      </common-info-table>

      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div> -->
    </common-info-dialog>
    <common-edit-dialog
      title="应用白名单"
      :visible.sync="passUrlOpen"
      @cancel="cancel"
      @submit="submitPassUrlForm"
      :buttonLoading="passUrlLoading"
      :info-loading="passUrlInfoLoading"
    >
      <el-form
        ref="form"
        :model="passUrlForm"
        :rules="rules"
        label-width="80px"
        @submit.native.prevent
      >
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item
              v-for="(item, index) in passUrlForm.passUrls"
              :key="index"
              :prop="'passUrls.' + index + '.value'"
              :label="`白名单 ${index === 0 ? '' : index}`"
            >
              <div class="control">
                <common-input
                  v-model="item.value"
                  placeholder="请输入"
                  :maxWidth="200"
                />
                <el-button
                  v-if="index <= 0"
                  class="control-button"
                  type="primary"
                  icon="plus"
                  plain
                  @click="handleAddPassUrl"
                  >新增</el-button
                >
                <el-button
                  class="control-button"
                  type="danger"
                  plain
                  @click="handleDeletePassUrl(index)"
                  >删除</el-button
                >
              </div>
            </el-form-item>
          </el-col></el-row
        >
      </el-form>
    </common-edit-dialog>
  </common-list>
</template>

<script>
import {
  listRoutesConfig,
  getRoutesConfig,
  delRoutesConfig,
  addRoutesConfig,
  updateRoutesConfig,
  getdictData,
  passUrlHandle,
  passUrlList,
} from "@/api/apisecurity/route/routesConfig";
import BaseList from "@/mixins/BaseList";
import { validateURL, validateSourceURL, validateURLOrNull } from "@/utils/formValidates";

export default {
  name: "RoutesConfig",
  components: {},
  mixins: [BaseList],
  data() {
    const checkInput = (rule, value, callback) => {
      if (value && value.length <= 5) {
        callback(new Error("请输入服务前缀"));
      } else {
        callback();
      }
    };
    return {
      passUrlOpen: false,
      passUrlLoading: false,
      passUrlInfoLoading: false,
      passUrlForm: {
        passUrls: [{ value: "" }],
      },
      infoLoading: false,
      infoUpdateLoading: false,
      isDataId: false,
      placeholders: "/system/**",
      controlTypeDisplay: false,
      filters: "",
      filtersValue: "",
      strategyDisplay: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务路由管理表格数据
      routesConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      detailsOpen: false,
      detailsTitle: "",
      predicatesHead: "Path=",
      predicates: "",
      filtersValueDisabled: true,
      // controlPolicy: [],
      // controlPolicyArr: [], // 管控策略
      // blacklistUrl: [1],
      // blacklistUrlArr: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        routeId: undefined,
        uri: undefined,
        predicates: undefined,
        filters: undefined,
        controlType: null,
        // blacklistUrl: undefined,
        // controlPolicy: undefined,
        status: undefined,
        sslStart: undefined,
        keyAlias: undefined,
        keyStoreType: undefined,
        keyStore: undefined,
        keyStorePassword: undefined,
        keyPassword: undefined,
        keyStoreProvider: undefined,
        routeName: null,
        dataId: null,
        controlType: null,
      },
      // 表单参数
      form: {},
      buttonLoading: false,
      dictData: [],
      // 表单校验
      rules: {
        routeName: [
          { required: true, message: "请输入路由名称", trigger: "blur" },
          { max: 30, message: "长度不能大于30个字符", trigger: "blur" },
        ],
        routeId: [
          { required: true, message: "请输入路由标识ID", trigger: "blur" },
          { max: 30, message: "长度不能大于30个字符", trigger: "blur" },
        ],
        uri: [
          { required: true, message: "请输入资源标识URL", trigger: "blur" },
          {
            required: true,
            message: "资源标识URL格式错误",
            validator: validateSourceURL,
            trigger: "blur",
          },
          { max: 100, message: "长度不能大于100个字符", trigger: "blur" },
        ],
        predicates: [
          { required: true, validator: checkInput, trigger: "blur" },
          { max: 100, message: "长度不能大于100个字符", trigger: "blur" },
        ],
        dataId: [
          { required: true, message: "请选择所属网关", trigger: "blur" },
        ],
        filters: [
          { required: true, message: "请选择过滤器规则", trigger: "blur" },
        ],
        controlType: [
          { required: true, message: "请选择认证方式", trigger: "blur" },
        ],
        tokenName: [
          { required: true, message: "请输入TOKEN参数名称", trigger: "blur" },
        ],
        tokenPosition: [
          { required: true, message: "请选择TOKEN位置", trigger: "blur" },
        ],
        checkAuthServer: [
          { required: true, message: "请输入鉴权接口", trigger: "blur" },
          {
            required: true,
            message: "鉴权接口格式错误",
            validator: validateURLOrNull,
            trigger: "blur",
          },
        ],
        authServer: [
          { required: true, message: "请输入授权接口", trigger: "blur" },
          {
            required: true,
            message: "授权接口格式错误",
            validator: validateURL,
            trigger: "blur",
          },
        ],
        oauthType: [
          { required: true, message: "请选择认证模式", trigger: "blur" },
        ],
        callCodeUrl: [
          { required: true, message: "请输入授权码接口", trigger: "blur" },
        ],
        secretKey: [{ required: true, message: "请输入秘钥", trigger: "blur" }],
        baseAddress: [
          { required: true, message: "请输入基准域名", trigger: "blur" },
        ],
        userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
        userPwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
        appKey: [{ required: true, message: "请输入appKey", trigger: "blur" }],
        appSecret: [
          { required: true, message: "请输入appSecret", trigger: "blur" },
        ],
        // paramPwd: [
        //   { required: true, message: "请输入密码参数名称", trigger: "blur" },
        // ],
        // paramUser: [
        //   { required: true, message: "请输入用户名参数名称", trigger: "blur" },
        // ],
      },
      routeId: "",
    };
  },
  watch: {
    // controlPolicyArr(val, oldVal) {
    //   this.form.controlPolicy = val;
    // },
    // blacklistUrlArr(val, oldVal) {
    //   this.form.blacklistUrl = val;
    // },
  },
  created() {
    this.getRoutesConfig();
    this.getdictData();
  },
  methods: {
    getPassUrl(row) {
      this.passUrlInfoLoading = true;
      this.passUrlOpen = true;
      this.routeId = row.routeId;
      passUrlList({ routeId: row.routeId })
        .then((res) => {
          if (res && res.code === 200) {
            if (res.data.length === 0) {
              this.passUrlForm.passUrls = [{ value: "" }];
            } else {
              this.passUrlForm.passUrls = res.data.reduce((r, c) => {
                r.push({
                  value: c.passUrl,
                });
                return r;
              }, []);
            }
          } else {
            this.passUrlForm.passUrls = [{ value: "" }];
          }
        })
        .finally(() => {
          this.passUrlInfoLoading = false;
        });
    },
    submitPassUrlForm() {
      this.passUrlLoading = true;
      let passUrls = [];
      this.passUrlForm.passUrls.map((item) => {
        item.value ? passUrls.push(item.value) : null;
      });
      passUrlHandle({
        routeId: this.routeId,
        passUrls: passUrls,
      })
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("编辑成功");
            this.passUrlOpen = false;
            this.getRoutesConfig();
          } else {
            this.$GlobalErrorConfirm("编辑失败", res.msg);
          }
        })
        .finally(() => {
          this.passUrlLoading = false;
        });
    },
    handleAddPassUrl() {
      this.passUrlForm.passUrls.push({});
    },
    handleDeletePassUrl(id) {
      if (id === 0) {
        this.passUrlForm.passUrls[0].value = "";
      } else {
        this.passUrlForm.passUrls.splice(id, 1);
      }
    },

    oauthTypeChange(val) {
      this.form.tokenName = "";
      this.form.tokenPosition = "";
      this.form.checkAuthServer = "";
      this.form.authServer = "";
      this.form.oauthType = "";
      this.form.paramPwd = "password";
      this.form.paramUser = "username";
      this.form.callCodeUrl = "";
      this.form.secretKey = "";
      this.form.baseAddress = "";
      this.form.userName = "";
      this.form.userPwd = "";
      this.form.appKey = "";
      this.form.appSecret = "";
      this.form.contentType = "application/json";
      this.form.remark = "";
      this.form.paramToken = "token";
      this.$refs.form.clearValidate([
        "appSecret",
        "appKey",
        "userPwd",
        "userName",
        "baseAddress",
        "secretKey",
        "callCodeUrl",
        "oauthType",
        "authServer",
        "checkAuthServer",
        "controlType",
        "tokenName",
        "tokenPosition",
      ]);
    },
    getdictData() {
      getdictData({ dictType: "GATEWAY_TYPE" }).then((res) => {
        if (res && res.code === 200) {
          this.dictData = res.data;
        } else {
          this.dictData = [];
        }
      });
    },
    controlTypeChange(row) {
      if (row === "" || row === "LIMIT") {
        // this.controlPolicyArr = [];
        this.controlTypeDisplay = false;
      } else {
        this.controlTypeDisplay = true;
      }
    },
    filtersChange(row) {
      if (row && row.length) {
        this.filtersValueDisabled = false;
      } else {
        this.filtersValue = "";
        this.filtersValueDisabled = true;
      }
    },
    predicatesHeadChange(row) {
      this.predicates = "";
      if (row === "Path=") {
        // this.strategyDisplay = true;
        this.placeholders = "/system/**";
      }
      if (row === "Host=") {
        // this.strategyDisplay = false;
        this.placeholders = "127.0.0.1:8888";
      }
    },

    /** 查询服务路由管理列表 */
    getRoutesConfig() {
      this.loading = true;
      listRoutesConfig(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.routesConfigList = res.rows;
            this.total = res.total;
          } else {
            this.routesConfigList = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.detailsOpen = false;
      this.passUrlOpen = false;
      this.reset();

      // this.reParams();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        routeId: null,
        uri: null,
        predicates: null,
        filters: null,
        controlType: "",
        // blacklistUrl: null,
        // controlPolicy: null,
        status: 0,
        delFlag: null,
        sslStart: null,
        keyAlias: null,
        keyStoreType: null,
        keyStore: null,
        keyStorePassword: null,
        keyPassword: null,
        keyStoreProvider: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        dataId: null,
        controlType: "0",
        Certification: null,
        requestID: null,
        password: null,
        location: "1",
        token: "1",
        authServer: null,
        secretKey: null,
        Callback: null,
        baseAddress: null,
        userName: null,
        userPwd: null,
        appKey: null,
        appSecret: null,
        checkAuthServer: null,
        oauthType: null,
        tokenPosition: null,
        remark: null,
        callCodeUrl: null,
        paramPwd: null,
        tokenName: null,
        paramUser: null,
        contentType: null,
        paramToken: null,
      };
      this.resetForm("form");
      this.predicates = "";
      this.filters = "";
      this.filtersValue = "";
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getRoutesConfig();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isDataId = false;
      this.reset();
      this.filtersValueDisabled = true;
      this.controlTypeDisplay = false;
      this.predicatesHead = "Path=";
      this.placeholders = "/system/**";
      // this.reParams();
      this.open = true;
      this.title = "新增路由管理";
      this.form.dataId = this.dictData[0]?.dictLabel;
      this.infoUpdateLoading = false;
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.isDataId = true;
      this.reset();
      // this.reParams();
      this.getInfo(row, 1);
    },
    getInfo(row, n) {
      // 1:编辑  2：详情
      const id = row.id || this.ids;
      if (n !== 1) {
        //详情
        this.detailsOpen = true;
        this.detailsTitle = "路由管理详情";
      } else {
        //编辑
        this.open = true;
        this.title = "编辑路由管理";
      }
      this.detail(id);
    },
    detail(id) {
      this.infoLoading = true;
      this.infoUpdateLoading = true;
      getRoutesConfig(id).then((res) => {
        if (res && res.code === 200) {
          this.form = res.data;
          if (this.form.filters !== "") {
            this.filters = this.form.filters.slice(0, 12);
            this.filtersValue = this.form.filters.slice(-1);
            this.filtersValueDisabled = false;
          }
          this.predicates = this.form.predicates.slice(5);
          if (
            this.form.controlType === "" ||
            this.form.controlType === "LIMIT"
          ) {
            this.controlTypeDisplay = false;
          } else {
            this.controlTypeDisplay = true;
          }

          this.predicatesHead = res.data.predicates.slice(0, 5);
          this.predicates = res.data.predicates.slice(5);
          // this.blacklistUrlArr = this.form.blacklistUrl
          //   ? this.form.blacklistUrl.split(",")
          //   : [];
          // if (this.blacklistUrlArr && this.blacklistUrlArr.length) {
          //   this.blacklistUrl = [];
          //   this.blacklistUrlArr.map((v) => {
          //     this.blacklistUrl.push(1);
          //   });
          // }

          // this.controlPolicyArr = this.form.controlPolicy
          //   ? this.form.controlPolicy.split(";")
          //   : [];
          // if (this.controlPolicyArr && this.controlPolicyArr.length) {
          //   this.controlPolicy = [];
          //   this.controlPolicyArr.map((v) => {
          //     this.controlPolicy.push(1);
          //   });
          // }

          this.infoLoading = false;
          this.infoUpdateLoading = false;
        } else {
          this.reset();
          this.$GlobalErrorConfirm("获取信息失败", res.msg, "重新加载").then(
            () => {
              this.detail(id);
            }
          );
        }
      });
    },
    // controlPolicyFn() {
    //   this.controlPolicy.push(1);
    // },
    // delcontrolPolicyFn(i) {
    //   this.controlPolicy.splice(i, 1);
    //   // this.controlPolicyArr.splice(i, 1);
    // },
    // blacklistUrlFn() {
    //   this.blacklistUrl.push(1);
    // },
    // delblacklistUrlFn(i) {
    //   this.blacklistUrl.splice(i, 1);
    //   this.blacklistUrlArr.splice(i, 1);
    // },
    /** 提交按钮 */
    submitForm() {
      if (
        this.filters &&
        this.filters.length &&
        this.filtersValue &&
        this.filtersValue
      ) {
        this.form.filters = this.filters + this.filtersValue;
      } else {
        this.form.filters = "";
      }
      this.form.predicates = this.predicatesHead + this.predicates;
      // let controlPolicy = [];
      // let isTrue = false;
      // if (this.controlPolicy && this.controlPolicy.length) {
      //   this.controlPolicy.forEach((item, index) => {
      //     if (this.controlPolicyArr && this.controlPolicyArr.length) {
      //       if (!this.controlPolicyArr[index]) {
      //         isTrue = true;
      //       } else {
      //         controlPolicy.push(this.controlPolicyArr[index]);
      //       }
      //     } else {
      //       isTrue = true;
      //     }
      //   });
      //   if (this.form.controlType === "" || this.form.controlType === "LIMIT") {
      //     isTrue = false;
      //   }
      // if (isTrue) return this.$GlobalErrorConfirm("提示", "请输入管控策略");
      // }
      // let blacklistUrl = [];
      // this.blacklistUrlArr && this.blacklistUrlArr.length
      //   ? this.blacklistUrlArr.map((v, i) => {
      //       blacklistUrl.push(v);
      //     })
      //   : null;
      let newFormParams = Object.assign({}, this.form, {
        // controlPolicy: controlPolicy.join(";"),
        // blacklistUrl: blacklistUrl.join(","),
        filters: this.form.filters,
      });
      if (this.form.controlType === "1" && this.form.checkAuthServer === "") {
        this.rules["checkAuthServer"][0].required = false;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateRoutesConfig(newFormParams)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                  this.open = false;
                  this.getRoutesConfig();
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addRoutesConfig(newFormParams)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                  this.open = false;
                  this.getRoutesConfig();
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    // reParams() {
    //   // this.controlPolicy = [1];
    //   // this.controlPolicyArr = [];
    //   this.blacklistUrl = [1];
    //   this.blacklistUrlArr = [];
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          delRoutesConfig({ ids }).then((res) => {
            if (res && res.code == 200) {
              // this.queryParams.pageNum = 1;
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.queryParams.pageNum > 1 &&
                ids.split(",").length === this.routesConfigList.length
              ) {
                this.queryParams.pageNum -= 1;
              }
              this.getRoutesConfig();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
.displayFlex {
  display: flex;
  margin-bottom: 10px;
  align-items: center;

  .delectCurrentParam {
    font-size: 16px;
    margin-left: 10px;
    cursor: pointer;
    text-align: center;
  }
}

::v-deep .el-input-group__prepend {
  background: #fff;
}
.place {
  display: flex;
  .placeType {
    ::v-deep .el-form-item__content {
    }
  }
  .parameters {
    width: calc(100% - 359px);
    ::v-deep .el-form-item__content {
      margin-left: 8px !important;
    }
  }
}
.control {
  display: flex;
  .control-button {
    margin-left: 8px;
  }
}
.check-auth-server {
  ::v-deep .el-form-item__label:before {
    display: none !important;
  }
}
</style>
